from django import forms
# from django.forms.forms import ValidationError # 这个也可以
from django.core.exceptions import ValidationError
from web import models
from web.forms.widgets import ColorRadioSelect
from utils.bootstrap import BootstrapModelForm,BootstrapForm

class ProjectCreateModelForm(BootstrapModelForm):
    bootstrap_class_exclude = ['color']

    # desc = forms.CharField(widget=forms.Textarea(attrs={'xx': 123}))
    class Meta:
        model = models.ProjectInfo
        fields = ['project_name', 'color', 'desc']
        widgets = {
            'desc': forms.Textarea(attrs={"xxx":123,"rows":5}),# 修改插件并自定义一些属性
            'color': ColorRadioSelect(attrs={'class': 'color-radio'})
        }

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request
    """ 校验项目 """
    def clean_project_name(self):
        # 1.判断当前用户是否已经创建同名项目
        exists = models.ProjectInfo.objects.filter(project_name=self.cleaned_data["project_name"],create_user=self.request.tracer.user).exists()
        if exists:
            raise ValidationError("该项目名已存在")
        # 2.判断当前用户是否还有额度创建新的项目
        project_total = self.request.tracer.price_policy.project_total
        current_total = models.ProjectInfo.objects.filter(create_user=self.request.tracer.user).count()
        print(f"当前用户可创建：{project_total}个项目",f"已创建{current_total}个项目")
        if current_total>=project_total:
            raise ValidationError("项目个数已用完，请购买套餐")
        return self.cleaned_data["project_name"]


class ProjectCreateForm(BootstrapForm):

    project_name = forms.CharField(label='项目名称')
# ''' 系统设置-删除项目 '''
class ProjectDeleteModelForm(BootstrapModelForm):
    xmmc = forms.ChoiceField(label="项目名称",widget=forms.Select(attrs={'class': "selectpicker", "data-live-search": "true"}))
    class Meta:
        model = models.ProjectInfo
        fields = "__all__"

    def __init__(self,request,*args,**kwargs):
        super().__init__(*args,**kwargs)
        self.request = request
        # xmmc = kwargs.pop('xmmc',None)
        total_list = [('','请选择要删除的项目')]
        project_list = models.ProjectInfo.objects.filter(create_user=request.tracer.user).values_list('id','project_name')
        total_list.extend(project_list)
        # self.fields['xmmc'].initial = xmmc
        self.fields['xmmc'].choices = total_list
        # '''自定义字段'''






